
// 未排序正数数组中累加和为给定值的最长子数组的长度
// 输出：[1,2,1,1,1] 3,,输出 3
function findMax(arr, target) {
  arr.sort((a, b) => a - b)
  let len = arr.length;
  let i = 0, j = 0;
  let sum = 0;
  let max = 0;
  while (j < len) {
    if (sum === target) {
      max = Math.max(max, j - i + 1);
      sum = sum - arr[i];
      i++;
    } else if (sum > target) {
      sum = sum - arr[i];
      i++;
    } else {
      j++;
      sum = sum + arr[j];
    }
  }
  return max;
}

const arr = [1, 2, 1, 1, 1]
console.log(findMax(arr, 3));